﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UIT.Controls.Containers;
using System.Windows.Markup;
using UIT.Controls.Template;
using UIT.Converters;
using UIT.Controls;
using UIT.Controls.Data;

namespace UIT.Web.Controls.Data
{
    public class Repeater : Control, IDataConsumer, IContainer
    {
        private IDataProvider dataSource;

        [System.ComponentModel.TypeConverter(typeof(DataProviderConverter))]
        public IDataProvider DataSource
        {
            get { return dataSource; }
            set
            {
                if (dataSource != null)
                    dataSource.Parent = null;
                dataSource = value;
                if (dataSource != null)
                    dataSource.Parent = this;
            }
        }


        public ITemplate ItemTemplate { get; set; }
        public ITemplate AlternatingItemTemplate { get; set; }
        public ITemplate SelectedItemTemplate { get; set; }

        public override bool IsContainer
        {
            get { return true; }
        }

        public override ControlType Type
        {
            get { return ControlType.List; }
        }

        #region IContainer Members

        private IDisposableObservableCollection<IContainer, IControl> children;

        public IDisposableObservableCollection<IContainer, IControl> Children
        {
            get
            {
                if (children == null && DataSource != null)
                {
                    children = new ControlCollection<IControl>(this);
                    DataBind();
                }
                return children;
            }
        }

        public void DataBind()
        {
            if (DataSource != null)
            {
                bool takeAlternatingTemplate = false;
                foreach (var item in DataSource.Select(new SelectArgument()))
                {
                    IControl itemInstance;
                    if (takeAlternatingTemplate && AlternatingItemTemplate != null)
                        itemInstance = AlternatingItemTemplate.CreateInstance(item);
                    else
                        itemInstance = ItemTemplate.CreateInstance(item);
                    takeAlternatingTemplate = !takeAlternatingTemplate;
                    if (itemInstance != null)
                        children.Add(itemInstance);
                }
            }
        }

        #endregion

        #region IDisposable Members

        public override void Dispose()
        {
            base.Dispose();

            if (children != null)
            {
                children.Dispose();
                children = null;
            }
        }

        #endregion
    }
}
